package com.example.backend.service;

import com.example.backend.entity.Admin;
import com.example.backend.mapper.AdminMapper;
import com.example.backend.util.PwdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import java.util.ArrayList;

@Service
public class AdminService {
    @Autowired
    private AdminMapper adminMapper;
    public Admin login(String name, String rawPwd) {
        // 1. 查库
        Admin admin = adminMapper.selectByAdminname(name);
        if (admin == null) {
            return null;           // 用户不存在
        }

        // 2. 把明文加密后与库里的比较
        String encrypted = PwdUtil.getEncryptedPwd(rawPwd);
        if (!admin.getPwd().equals(encrypted)) {
            return null;           // 密码错误
        }
        admin.setPwd(null);        // 3. 返回前擦除密码
        return admin;
    }

    public int doRegister(Admin admin) {
        admin.setPwd(PwdUtil.getEncryptedPwd(admin.getPwd()));
        return adminMapper.doRegister(admin);
    }

    public int doUpdate(Admin admin){
        if (admin.getPwd() != null && !admin.getPwd().isEmpty()) {
            admin.setPwd(PwdUtil.getEncryptedPwd(admin.getPwd()));
        }
        return adminMapper.doUpdate(admin);
    }
    public int doDelete(String id){
        int count = adminMapper.doDelete(id);
        return count;
    }
    public Admin getAdminById(String id){
        Admin admin = adminMapper.getAdminById(id);
        return admin;
    }
    public Map<String, Object> doList(Admin admin, int pageNum, int pageSize) {
        // 使用传入的分页参数启动分页
        PageHelper.startPage(pageNum, pageSize);

        // 执行数据库查询 - 这里保持不变
        ArrayList<Admin> admins = adminMapper.doList(admin);

        // 创建PageInfo对象获取分页信息
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);

        // 构建包含数据和分页信息的响应
        Map<String, Object> result = new HashMap<>();
        result.put("list", admins);          // 当前页的数据列表
        result.put("total", pageInfo.getTotal()); // 总记录数
        result.put("pages", pageInfo.getPages()); // 总页数

        return result;
    }

    public Admin selectByAdminname(String name){
        Admin admin = adminMapper.selectByAdminname(name);
        return admin;
    }
    //

}